import { createI18n } from "vue-i18n"
import initEn from "@/locale/uni-app.en.json"
import en from "@/locale/en"
import initZhHans from "@/locale/uni-app.zh-Hans.json"
import zhHans from "@/locale/zh-Hans"
import type { MergeUnion } from "@/utils/type"

const arr = [
  ['en', initEn, en],
  ['zh-Hans', initZhHans, zhHans]
] as const
const messages = arr.reduce((p, c) => {
  const [name, init, expand] = c
  
  // 不直接设置值的原因是 vue-i18n 的 t 函数无法识别可选字段
  Reflect.set(p, name, { ...init, ...expand })
  return p
}, <{
  [x in typeof arr[number][0]]: RequiredDeep<MergeUnion.MergeOption<typeof arr[number][1]['common']  & typeof arr[number][2]>>
}>{})

export const i18n = createI18n({
  locale: uni.getLocale(),
  messages
})

export const t = i18n.global.t
export const setLanguage = (language: keyof typeof messages) => {
  if (uni.getLocale() === language) return
  uni.setLocale(language)
  // #ifdef H5
  location.reload()
  // #endif
  // #ifdef APP-PLUS
  if(uni.getSystemInfoSync().osName === 'ios') plus.runtime.restart()
  // #endif
}